//
//  BZUserAccount.swift
//  weibo
//
//  Created by zzx on 2017/7/30.
//  Copyright © 2017年 zzx. All rights reserved.
//

import UIKit
//归档和解档路径
let UserAccountPath = ( NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")


//用户模型
class BZUserAccount: NSObject,NSCoding {

    //访问令牌
    var access_token: String?
    
    //access_token的剩余时间，单位是秒数
    var expires_in: Int = 0 {
        didSet {
        
            expiresDate = Date().addingTimeInterval(TimeInterval(expires_in))
            
        }
        
    }
    
    //过期时间对象
    var expiresDate: Date?
    
    //用户id
    var uid: Int64 = 0
    
    //用户名称
    var name: String?
    
    //用户头像
    var avatar_large: String?
    
    //kvc构造函数
    init(dic: [String: Any]) {
        super.init()
        
        setValuesForKeys(dic)
        
    }
    
    //防止字段重复
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        //空
    }
    
    //MARK:- 解档和归档
    //归档
    func encode(with aCoder:NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
    }
    
    //解档
    required init?(coder aDecoder:NSCoder){
        
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        
        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? Date
        
        uid = aDecoder.decodeInt64(forKey: "uid")
        
        name = aDecoder.decodeObject(forKey: "name") as? String
        
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String

    }
    
    //保存用户对象
    func saveUseAccount() {
        
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccountPath)
        
    }
    
    //读取用户对象
    class func loadUserAccount() -> BZUserAccount? {
        print(UserAccountPath)
        
        let userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: UserAccountPath) as? BZUserAccount
        
        return userAccount
        
        
    }
    
    
}







